package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.common.BaseContext;
import com.project.dto.*;
import com.project.dtoplus.*;
import com.project.entity.*;
import com.project.mapper.*;
import com.project.service.*;
import com.project.utils.AliOSSUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cglib.core.Local;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProEteacherService proEteacherService;
    @Autowired
    private ProMemberService proMemberService;
    @Autowired
    private AccessoryService accessoryService;

    @Autowired
    private ProjectService projectService;
    
    @Autowired
    private AliOSSUtils aliOSSUtils;

    @Autowired
    private LogsService logsService;

    @Autowired
    private UserMemberService userMemberService;

    @Autowired
    private LogCountService logCountService;

    @Autowired
    private ProPaperService proPaperService;

    @Autowired
    private ProPatentService proPatentService;

    @Autowired
    private ProEntityService proEntityService;

    @Autowired
    private ProTeacherDtoMapper proTeacherDtoMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private LogsMapper logsMapper;

    @Autowired
    private GlobalTimeMapper globalTimeMapper;

    @Autowired
    private LogCountMapper logCountMapper;

    @Autowired
    private UserMemberMapper userMemberMapper;

    @Autowired
    private ProMemberMapper proMemberMapper;

    public static int sortMain;

    @Autowired
    private ChangeMapper changeMapper;

    //1.项目申报

    public void apply(ProjectDto projectDto)  {
        projectDto.setDeclareTime(LocalDateTime.now());
        projectService.save(projectDto);

        ProEteacher proEteacher = projectDto.getProEteacher();
        //保存企业老师
        if(proEteacher!=null) {
            proEteacher.setProjectId(projectDto.getId());
            proEteacherService.save(proEteacher);
        }

        //保存学生信息
         List<Member> members=  projectDto.getStuIds();
        String[] works = projectDto.getWorks();
        for(int i=0;i<members.size() ;i++){
            ProMember proMember=new ProMember();
            proMember.setUserId(members.get(i).getUserId());
            proMember.setWork(works[i]);
            proMember.setProjectId(projectDto.getId());
            proMember.setSort(i);
            proMember.setMasterUserId(members.get(0).getUserId());
            proMemberService.save(proMember);
        }
        //保存附件信息
        List<Accessory> accessories = projectDto.getAccessories().stream().map((item)->{
            Accessory accessory=new Accessory();
            accessory.setProjectId(projectDto.getId());
            accessory.setType(0);
            accessory.setName(item.getName());
            accessory.setAccessory(item.getUrl());
            accessory.setUpTime(LocalDateTime.now());
            accessory.setUserId(BaseContext.getCurrentId());
            return accessory;
        }).collect(Collectors.toList());


        for (Accessory accessory : accessories) {

            accessoryService.save(accessory);
        }

        //创建一条日志信息 使项目状态为立项审核中
        Logs log =new Logs();
        log.setProjectId(projectDto.getId());
        log.setStatus(0);
        log.setLevel(1);//立项审核中
        logsService.save(log);
        //增加中期审核日志
        Logs logMid=new Logs();
        logMid.setProjectId(projectDto.getId());
        logMid.setStatus(1);
        logMid.setLevel(0);//未中期审核
        logsService.save(logMid);
        //增加结项日志
        Logs logEnd=new Logs();
        logEnd.setProjectId(projectDto.getId());
        logEnd.setStatus(2);
        logEnd.setLevel(0);//为结项审核
        logsService.save(logEnd);
        //大创日志
        LogCount logCount=new LogCount();
        logCount.setCount(0);
        logCount.setProjectId(projectDto.getId());
        logCountService.save(logCount);

        //创建项目成员是否修改数据库
        Change change=new Change();
        change.setId(projectDto.getId());
        change.setMid(0);
        changeMapper.save(change);
    }
    //项目申请时添加附件
    public List<AnnexPlus> addBeginAccessory(MultipartFile[] files,int type) throws IOException {
        List<String> upload = aliOSSUtils.upload(files);
        List<Accessory> accessories=new ArrayList<>();
        List<AnnexPlus> annexPluses=new ArrayList<>();

        int i = 0;
        for (MultipartFile file : files) {
            String name = file.getOriginalFilename();
            AnnexPlus annexPlus=new AnnexPlus();
            annexPlus.setName(name);
            annexPlus.setUrl(upload.get(i));
            annexPluses.add(annexPlus);
        }
        return annexPluses;
    }
    //2.添加中期附件
    public void addAccessory( List<AnnexPlus> annexPluses,Long projectId,int type) throws IOException {
        //如果有附件，先删除
        LambdaQueryWrapper<Accessory> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Accessory::getProjectId,projectId);
        queryWrapper.eq(Accessory::getType,type);
        List<Accessory> list = accessoryService.list();
        if(list!=null){
            accessoryService.remove(queryWrapper);
        }
        List<Accessory> accessories=annexPluses.stream().map((item)->{
            Accessory accessory=new Accessory();
            accessory.setProjectId(projectId);
            accessory.setUserId(BaseContext.getCurrentId());
            accessory.setName(item.getName());
            accessory.setType(type);
            accessory.setAccessory(item.getUrl());
            accessory.setUpTime(LocalDateTime.now());
            return accessory;
        }).collect(Collectors.toList());
        accessoryService.saveBatch(accessories);
        //更新日志
        logsMapper.updateLevel(projectId,type,1);


        Set keys = redisTemplate.keys("*_" + projectId);
        redisTemplate.delete(keys);


    }

    //3.获取项目详情
    public ProjectDetailPlus detail(Long projectId){
        ProjectPartDto projectPartDto=new ProjectPartDto();

        Project project = projectService.getById(projectId);
        BeanUtils.copyProperties(project,projectPartDto);

        //获取企业老师信息
        LambdaQueryWrapper<ProEteacher> proEteacherLambdaQueryWrapper=new LambdaQueryWrapper<>();
        proEteacherLambdaQueryWrapper.eq(ProEteacher::getProjectId,projectId);
        ProEteacher proEteacherServiceOne = proEteacherService.getOne(proEteacherLambdaQueryWrapper);
        if(proEteacherServiceOne!=null) {
            projectPartDto.setProEteacher(proEteacherServiceOne);
        }
        //获取项目成员信息
        List<Member> members=new ArrayList<>();
        LambdaQueryWrapper<ProMember> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ProMember::getProjectId,projectId);
        List<ProMember> list = proMemberService.list(queryWrapper);
        List<Member> member=list.stream().map((item)->{
            Member memberOne=new Member();
            LambdaQueryWrapper<UserMember> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(UserMember::getUserId,item.getUserId());
            UserMember serviceOne = userMemberService.getOne(wrapper);
            memberOne.setDepartment(serviceOne.getDepartment());
            memberOne.setMajor(serviceOne.getMajor());
            memberOne.setPhone(serviceOne.getPhone());
            memberOne.setName(serviceOne.getName());
            memberOne.setUserId(serviceOne.getUserId());
            return memberOne;
        }).collect(Collectors.toList());
        projectPartDto.setMembers(member);

        //获取附件
        LambdaQueryWrapper<Accessory> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(Accessory::getProjectId ,projectId);
        List<Accessory> accessories = accessoryService.list(queryWrapper1);
        projectPartDto.setAccessories(accessories);
        ProjectDetailPlus detailPlus = this.getDetailPlus(projectPartDto);

        return detailPlus;


    }
    //4.项目审核
    public void auditPro (Logs logs,int status){

        LambdaQueryWrapper<Logs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Logs::getProjectId, logs.getProjectId());
        queryWrapper.eq(Logs::getStatus, status);
        Logs log = logsService.getOne(queryWrapper);
        if(logs.getGradeOne()!=null&&logs.getGradeTwo()!=null&&logs.getGradeThree()!=null
                &&logs.getGrade()!=null &&logs.getIsPass()!=null) {
            if(logs.getIsPass()==1&&log.getLevel()<4) {//通过
                logs.setLevel(2);
                logs.setErrorMsg("空");
                logs.setUserId(BaseContext.getCurrentId());
                logsService.update(logs, queryWrapper);
            }else if(logs.getIsPass()==0&&log.getLevel()<4){//未通过
                logs.setLevel(3);
                logs.setUserId(BaseContext.getCurrentId());
                logsService.update(logs, queryWrapper);
            }

            //延期审核
            if(logs.getIsPass()==1&&log.getLevel()>4){//延期审核通过
                logs.setLevel(6);
                logs.setErrorMsg("空");
                logs.setUserId(BaseContext.getCurrentId());
                logsService.update(logs,queryWrapper);
            }else if(logs.getIsPass()==0&&log.getLevel()>4){//延期审核未通过
                logs.setLevel(7);
                logs.setErrorMsg("空");
                logs.setUserId(BaseContext.getCurrentId());
                logsService.update(logs,queryWrapper);
            }
            //redis
            Set keys = redisTemplate.keys("*_" + logs.getProjectId());
            redisTemplate.delete(keys);

        }


    }
    //5.立项审核项目列表
        public Page establishment (int page, int pageSize,String name){
        Page<Project> page1=new Page<>(page,pageSize);
        Page<ProBeginPage> beginPage=new Page<>();

        //构建条件构造器
            LambdaQueryWrapper<Project> queryWrapper=new LambdaQueryWrapper<>();

            queryWrapper.like(name!=null,Project::getName,name);
            queryWrapper.orderByDesc(Project::getDeclareTime);

            projectService.page(page1,queryWrapper);


        //对象拷贝
            BeanUtils.copyProperties(page1,beginPage,"records");
            List<Project> records = page1.getRecords();
            List<ProBeginPage> list=records.stream().map((item)->{
                 //redis
                ProBeginPage projectBegin=null;
                String key="establishment_"+item.getId();
                projectBegin=(ProBeginPage) redisTemplate.opsForValue().get(key);
                if(projectBegin!=null){
                    return  projectBegin;
                }

                projectBegin=new ProBeginPage();
                Long projectId = item.getId();
        //基本信息
                projectBegin.setId(item.getId());
                projectBegin.setCategory(item.getCategory());
                projectBegin.setDeclareTime(item.getDeclareTime());
                projectBegin.setName(item.getName());

        //老师信息
                LambdaQueryWrapper<UserMember> teacher =new LambdaQueryWrapper<>();
                teacher.eq(UserMember::getUserId,item.getTutorId());
                UserMember teach = userMemberService.getOne(teacher);
                projectBegin.setTeacher(teach.getName());
        //学生信息
                LambdaQueryWrapper<ProMember> queryWrapper1=new LambdaQueryWrapper<>();
                queryWrapper1.eq(ProMember::getProjectId,projectId);
                queryWrapper1.eq(ProMember::getSort,0);//负责人
                ProMember one = proMemberService.getOne(queryWrapper1);
                LambdaQueryWrapper<UserMember> lambdaQueryWrapper=new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(UserMember::getUserId,one.getUserId());
                UserMember serviceOne = userMemberService.getOne(lambdaQueryWrapper);
                projectBegin.setTutor(serviceOne.getName());
                projectBegin.setDepartment(serviceOne.getDepartment());

         //status
                LambdaQueryWrapper<Logs> logsLambdaQueryWrapper=new LambdaQueryWrapper<>();
                logsLambdaQueryWrapper.eq(Logs::getProjectId,projectId);
                logsLambdaQueryWrapper.eq(Logs::getStatus,0);
                Logs log = logsService.getOne(logsLambdaQueryWrapper);
                if(log.getLevel()==1){
                    projectBegin.setStatus("立项审核中");
                    projectBegin.setLevel(1);
                }else if(log.getLevel()==2){
                    projectBegin.setStatus("立项审核通过");
                    projectBegin.setLevel(2);
                }else if(log.getLevel()==3){
                    projectBegin.setStatus("立项审核未通过");
                    projectBegin.setLevel(3);
                }
         //flag(0：没选项 1：提交材料, 2:详情)
                if(log.getLevel()==1||log.getLevel()==2){
                    projectBegin.setFlag(0);
                }else if(log.getLevel()==3){
                    projectBegin.setFlag(2);
                }
                redisTemplate.opsForValue().set(key,projectBegin,60, TimeUnit.MINUTES);
                return projectBegin;
            }).collect(Collectors.toList());


            beginPage.setRecords(list);

            return beginPage;

        }
    //6.未通过时的详情
    public ProjectInfo msgInfo(int status,Long projectId){
        //获取错误信息
        LambdaQueryWrapper<Logs> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Logs::getProjectId,projectId);
        queryWrapper.eq(Logs::getStatus,status);
        Logs logsServiceOne = logsService.getOne(queryWrapper);
        String errorMsg = logsServiceOne.getErrorMsg();
        ProjectInfo projectInfo=new ProjectInfo();
        projectInfo.setMsg(errorMsg);

        //获取项目
        Project byId = projectService.getById(projectId);
        projectInfo.setName(byId.getName());
        projectInfo.setProjectId(byId.getId());
        projectInfo.setCategory(byId.getCategory());
        //获取老师姓名
        String tutorName = userMemberMapper.getName(byId.getTutorId());
        projectInfo.setTutorName(tutorName);

        //获取负责人
        Long masterId = proMemberMapper.getMasterId(byId.getId());
        projectInfo.setMasterId(masterId);
        String name = userMemberMapper.getName(masterId);
        projectInfo.setMasterName(name);

        return projectInfo;

    }
    //7.项目日志审核
    public void auditLogs(LogCount logCount){
        LogCount logCountMapperLog = logCountMapper.getLog(logCount.getProjectId());
        if(logCountMapperLog==null){
            logCount.setCount(1);

        }else {
            logCount.setCount(logCountMapperLog.getCount() + 1);
        }
            logCountService.save(logCount);

        //redis
        Set keys=redisTemplate.keys("*_"+logCount.getProjectId());
        redisTemplate.delete(keys);


    }
    //8.项目进展
    public Page logCount(int page,int pageSize,String name){
        //分页构造器
        Page<Project> page1=new Page<>(page,pageSize);
        Page<ProjectSchedule> pageInfo=new Page<>();

        //条件构造器
        LambdaQueryWrapper<Project> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Project::getName,name);
        queryWrapper.orderByDesc(Project::getDeclareTime);
        this.page(page1,queryWrapper);


        //对象拷贝
        BeanUtils.copyProperties(page1,pageInfo,"records");
        List<Project> records = page1.getRecords();
        List<ProjectSchedule> list=records.stream().map((item)->{
            //redis
            ProjectSchedule projectSchedule=null;
            String key="logCount_"+item.getId();
            projectSchedule=(ProjectSchedule)redisTemplate.opsForValue().get(key);
            if(projectSchedule!=null){
                return projectSchedule;
            }
            projectSchedule=new ProjectSchedule();

            BeanUtils.copyProperties(item,projectSchedule);
            //老师姓名
            LambdaQueryWrapper<UserMember> teacherName=new LambdaQueryWrapper<>();
            teacherName.eq(UserMember::getUserId,item.getTutorId());
            UserMember serviceOne = userMemberService.getOne(teacherName);
            projectSchedule.setTeacher(serviceOne.getName());
            //负责人姓名
            LambdaQueryWrapper<ProMember> tutor=new LambdaQueryWrapper<>();
            tutor.eq(ProMember::getProjectId,item.getId());
            tutor.eq(ProMember::getSort,0);
            ProMember proTutor = proMemberService.getOne(tutor);
            LambdaQueryWrapper<UserMember> userTutor=new LambdaQueryWrapper<>();
            userTutor.eq(UserMember::getUserId,proTutor.getUserId());
            UserMember userMember = userMemberService.getOne(userTutor);
            projectSchedule.setTutor(userMember.getName());
            Long id = item.getId();

        //获取大创日志
            LogCount logOne = logCountMapper.getLog(id);
            if(logOne==null){
            projectSchedule.setLogCount(0);
        }else {
            projectSchedule.setLogCount(logOne.getCount());
        }
            //redis
            redisTemplate.opsForValue().set(key,projectSchedule,60, TimeUnit.MINUTES);
         return projectSchedule;
        }).collect(Collectors.toList());
        pageInfo.setRecords(list);


        return  pageInfo;
    }
    //9.中期审核列表
    public Page pageMid(int page,int pageSize,String name){
        //分页构造器
        Page<Project> projectPage=new Page<>(page,pageSize);
        Page<ProMinPage> pageInfo=new Page<>();

        //条件构造器
        LambdaQueryWrapper<Project> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Project::getName,name);
        queryWrapper.orderByDesc(Project::getDeclareTime);
        this.page(projectPage,queryWrapper);



        //对象拷贝
        BeanUtils.copyProperties(projectPage,pageInfo,"records");
        List<Project> records = projectPage.getRecords();

        List<ProMinPage>  list=records.stream().map((item)->{
             //redis
             ProMinPage projectMid=null;
             String key="mid_term_"+item.getId();
             projectMid=(ProMinPage) redisTemplate.opsForValue().get(key);
             if(projectMid!=null){
                 return projectMid;
             }

            projectMid=new ProMinPage();

            BeanUtils.copyProperties(item,projectMid);
            //是否修改
            projectMid.setChange(changeMapper.getChange(item.getId()));
            //老师信息
            LambdaQueryWrapper<UserMember> teacher =new LambdaQueryWrapper<>();
            teacher.eq(UserMember::getUserId,item.getTutorId());
            UserMember teach = userMemberService.getOne(teacher);
            projectMid.setTeacher(teach.getName());

            Long id = item.getId();
           //负责人信息
            List<String> memberMapperMembers = proMemberMapper.getMembers(id);//全部成员
            Long masterId = proMemberMapper.getMasterId(id);
            String masterName = proMemberMapper.getMasterName(masterId);//负责人姓名
            projectMid.setTutor(masterName);
             memberMapperMembers.remove(masterName);
             //去除负责人过后的成员
            projectMid.setMember(memberMapperMembers);

            //获取全局时间
            LocalDateTime begin = globalTimeMapper.getBegin(1, item.getId());
            LocalDateTime end = globalTimeMapper.getEnd(1, item.getId());
            projectMid.setBegin(begin);
            projectMid.setEnd(end);

            //status


            LambdaQueryWrapper<Logs> logsLambdaQueryWrapper=new LambdaQueryWrapper<>();
            logsLambdaQueryWrapper.eq(Logs::getProjectId,id);
            logsLambdaQueryWrapper.eq(Logs::getStatus,1  );
            Logs logMid = logsService.getOne(logsLambdaQueryWrapper);
            // 到期未提交报告
            if(end!=null){
            if(end.compareTo(LocalDateTime.now())<0&&logMid.getLevel()==0) {//到期未提交
                projectMid.setFlag(0);
                projectMid.setLevel(3);
                projectMid.setStatus("中期审核未通过");
                }
            }
            //是否满足大创日志为10次
            LogCount logCount = logCountMapper.getLog(id);


            //获取立项数据，判断中期是否可以提交
            LambdaQueryWrapper<Logs> beginQueryWrapper=new LambdaQueryWrapper<>();
            beginQueryWrapper.eq(Logs::getProjectId,id);
            beginQueryWrapper.eq(Logs::getStatus,0);
            Logs beginLog = logsService.getOne(beginQueryWrapper);
            if(beginLog.getLevel()!=2){
                projectMid.setFlag(0);
                projectMid.setLevel(0);
                projectMid.setStatus("未中期审核");
            }

            else if (logCount.getCount()>=10){//直接通过
                projectMid.setFlag(0);
                projectMid.setLevel(4);
                projectMid.setStatus("中期审核通过");
                //更新数据库
                logsMapper.updateLevel(id,1,4);
            }  else if (logMid.getLevel()==3) {
                projectMid.setFlag(2);
                projectMid.setLevel(3);
                projectMid.setStatus("中期审核未通过");
            }else if(logMid.getLevel()==2||logMid.getLevel()==1){
                projectMid.setFlag(0);
                projectMid.setLevel(1);
                projectMid.setStatus("中期审核中");
            }else if(logMid.getLevel()==0){
                projectMid.setFlag(1);
                projectMid.setLevel(0);
                projectMid.setStatus("未中期审核");
            }
            //redis
            redisTemplate.opsForValue().set(key,projectMid,60, TimeUnit.MINUTES);
            return  projectMid;
        }).collect(Collectors.toList());
        pageInfo.setRecords(list);


        return  pageInfo;

    }
    //10.中期成员变更
    public void changeMember(Long projectId,String[] userIds,String[] works){

        //删除
        LambdaQueryWrapper<ProMember> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ProMember::getProjectId,projectId);
        LambdaQueryWrapper<ProMember> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(ProMember::getProjectId,projectId);
        List<ProMember> list = proMemberService.list();
        queryWrapper.eq(ProMember::getSort,0);
        ProMember proMember = proMemberService.getOne(queryWrapper);//主负责人
        proMemberService.remove(queryWrapper1);//删除所有人员

        //更改是否修改次数
        changeMapper.changeIF(projectId);

        //插入
        List<ProMember> proMembers=new ArrayList<>();
        proMembers.add(proMember);
        for (int i = 1; i <=userIds.length; i++){
            ProMember memberPro=new ProMember();
            memberPro.setProjectId(proMember.getProjectId());
            memberPro.setSort(i);
            memberPro.setWork(works[i-1]);
            memberPro.setUserId(Long.valueOf(userIds[i-1]));
            memberPro.setMasterUserId(proMember.getUserId());
            proMembers.add(memberPro);
        }
        proMemberService.saveBatch(proMembers);
        changeMapper.changeIF(projectId);
        //redis
        Set keys=redisTemplate.keys("*_"+projectId);
        redisTemplate.delete(keys);
    }

    //11.结项审核列表
    public Page pageFinish(int page,int pageSize,String name){
        //分页构造器
        Page<Project> projectPage=new Page<>(page,pageSize);
        Page<ProEndPage> pageInfo=new Page<>();

        //条件构造器
        LambdaQueryWrapper<Project> queryWrapper=new LambdaQueryWrapper<>();
        if(name!=null){
            queryWrapper.like(Project::getName,name);
        }
        queryWrapper.orderByDesc(Project::getDeclareTime);
        projectService.page(projectPage,queryWrapper);



        //对象拷贝
        BeanUtils.copyProperties(projectPage,pageInfo,"records");
        List<Project> records = projectPage.getRecords();
        List<ProEndPage> list=records.stream().map((item)->{
             //redis
             ProEndPage projectEnd=null;
             String key="submit_closeFiles_"+item.getId();
             projectEnd=(ProEndPage) redisTemplate.opsForValue().get(key);
             if(projectEnd!=null){
                return projectEnd;
             }

            projectEnd=new ProEndPage();

            BeanUtils.copyProperties(item,projectEnd);
            Long id = item.getId();
            //老师信息
            LambdaQueryWrapper<UserMember> teacher =new LambdaQueryWrapper<>();
            teacher.eq(UserMember::getUserId,item.getTutorId());
            UserMember teach = userMemberService.getOne(teacher);
            projectEnd.setTeacher(teach.getName());
            //负责人信息
            List<String> memberMapperMembers = proMemberMapper.getMembers(id);//全部成员
            Long masterId = proMemberMapper.getMasterId(id);
            String masterName = proMemberMapper.getMasterName(masterId);//负责人姓名
            projectEnd.setTutor(masterName);
            memberMapperMembers.remove(masterName);
            //去除负责人过后的成员
            projectEnd.setMember(memberMapperMembers);



        //status
            Logs logEnd = logsMapper.getLogs(id, 2);
            Logs logMid = logsMapper.getLogs(id, 1);
            if(logMid.getLevel()!=4){//中期审核还未通过
                projectEnd.setFlag(0);
                projectEnd.setLevel(0);
                projectEnd.setStatus("未结项审核");

            }
          else  if(logEnd.getLevel()<4){//没有延期申请
                if(logEnd.getLevel()==0){
                    projectEnd.setFlag(1);
                    projectEnd.setLevel(0);
                    projectEnd.setStatus("未结项审核");
                }else if(logEnd.getLevel()==1){
                    projectEnd.setFlag(0);
                    projectEnd.setLevel(1);
                    projectEnd.setStatus("结项审核中");
                }else if(logEnd.getLevel()==2){
                    projectEnd.setFlag(0);
                    projectEnd.setLevel(2);
                    projectEnd.setStatus("结项审核通过");
                }else if(logEnd.getLevel()==3){
                    projectEnd.setFlag(2);
                    projectEnd.setLevel(3);
                    projectEnd.setStatus("结项审核未通过");
                }

            }else if(logEnd.getLevel()>4){//提交了延期
                if(logEnd.getLevel()==5){
                    projectEnd.setFlag(0);
                    projectEnd.setLevel(5);
                    projectEnd.setStatus("延期审核中");}
            else if(logEnd.getLevel()==6){
                    projectEnd.setFlag(0);
                    projectEnd.setLevel(6);
                    projectEnd.setStatus("延期审核通过");
                }else if(logEnd.getLevel()==7){
                    projectEnd.setFlag(2);
                    projectEnd.setLevel(7);
                    projectEnd.setStatus("延期审核未通过");
                }

            }


            redisTemplate.opsForValue().set(key,projectEnd,60, TimeUnit.MINUTES);
            return projectEnd;
        }).collect(Collectors.toList());
        pageInfo.setRecords(list);

        return pageInfo;
    }

    //12.提交延期申请
    public void addExtension(String extensionMsg,Long projectId,int type) throws IOException {
        //保存延期信息
        logsMapper.changeMsg(extensionMsg,projectId,type);
        //更新状态
        logsMapper.updateLevel(projectId,type,5);

        logsMapper.changeUserId(projectId,type,BaseContext.getCurrentId());

        Set keys = redisTemplate.keys("*_" + projectId);
        redisTemplate.delete(keys);


    }

    //13.进入结项提交页面
    public ProPartPlus toClose(Long projectId){
        ProjectPartDto projectPartDto=new ProjectPartDto();

        Project project = projectService.getById(projectId);
        BeanUtils.copyProperties(project,projectPartDto);
        //老师信息
        LambdaQueryWrapper<Project> projectTeacher=new LambdaQueryWrapper<>();
        projectTeacher.eq(Project::getId,projectId);
        Project one = this.getOne(projectTeacher);

        LambdaQueryWrapper<UserMember> teacher =new LambdaQueryWrapper<>();
        teacher.eq(UserMember::getUserId,one.getTutorId());
        UserMember teach = userMemberService.getOne(teacher);
        projectPartDto.setTeacher(teach.getName());

        //获取项目成员信息

        LambdaQueryWrapper<ProMember> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ProMember::getProjectId,projectId);
        List<ProMember> list = proMemberService.list(queryWrapper);
        List<Member> members=list.stream().map((item)->{
            Member member=new Member();
            LambdaQueryWrapper<UserMember> pro =new LambdaQueryWrapper<>();
            pro.eq(UserMember::getUserId,item.getUserId());
            UserMember serviceOne = userMemberService.getOne(pro);
            member.setUserId(item.getUserId());
            member.setName(serviceOne.getName());
            return member;
        }).collect(Collectors.toList());
        projectPartDto.setMembers(members);

        //获取附件
        LambdaQueryWrapper<Accessory> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(Accessory::getProjectId ,projectId);
        List<Accessory> accessories = accessoryService.list(queryWrapper1);
        projectPartDto.setAccessories(accessories);

        ProPartPlus endConcise = this.getEndConcise(projectPartDto);

        return endConcise;


    }
    //14.提交结项资料
    public void finishAnnex(ProjectFinish projectFinish){
        //先判断
        //论文
        LambdaQueryWrapper<ProPaper> paperLambdaQuery=new LambdaQueryWrapper<>();
        paperLambdaQuery.eq(ProPaper::getProjectId,projectFinish.getProjectId());
        ProPaper paper = proPaperService.getOne(paperLambdaQuery);
        if (paper!=null){
            proPaperService.removeById(paper);
        }
        LambdaQueryWrapper<ProPatent> patentLambdaQuery=new LambdaQueryWrapper<>();
        patentLambdaQuery.eq(ProPatent::getProjectId,projectFinish.getProjectId());
        ProPatent patent = proPatentService.getOne(patentLambdaQuery);
        if (patent!=null){
            proPatentService.removeById(patent);
        }

        LambdaQueryWrapper<ProEntity> entityLambdaQuery=new LambdaQueryWrapper<>();
        entityLambdaQuery.eq(ProEntity::getProjectId,projectFinish.getProjectId());
        ProEntity entity = proEntityService.getOne(entityLambdaQuery);
        if (entity!=null){
            proEntityService.removeById(entity);
        }
        ProEntity proEntity = projectFinish.getProEntity();
        if(proEntity!=null) {

            proEntityService.save(proEntity);
        }
        //保存
        ProPaper proPaper = projectFinish.getProPaper();
        if(proPaper!=null){
        proPaperService.save(proPaper);}

        ProPatent proPatent = projectFinish.getProPatent();
        if(proPatent!=null) {

            proPatentService.save(proPatent);
        }
        logsMapper.updateLevel(projectFinish.getProjectId(),2,1);

        //保存附件
        //先查询是否有公告
        LambdaQueryWrapper<Accessory> accessoryLambdaQuery=new LambdaQueryWrapper<>();
        accessoryLambdaQuery.eq(Accessory::getProjectId,projectFinish.getProjectId());
        accessoryLambdaQuery.eq(Accessory::getType,2);
        List<Accessory> accessoryList = accessoryService.list(accessoryLambdaQuery);
        if(accessoryList!=null){
            accessoryService.remove(accessoryLambdaQuery);
        }
        //保存
        List<AnnexPlus> list = projectFinish.getAnnexPlus();
        if(list!=null) {
            List<Accessory> accessories = list.stream().map((item) -> {
                Accessory accessory = new Accessory();
                accessory.setProjectId(projectFinish.getProjectId());
                accessory.setType(2);
                accessory.setName(item.getName());
                accessory.setAccessory(item.getUrl());
                accessory.setUpTime(LocalDateTime.now());
                accessory.setUserId(BaseContext.getCurrentId());
                return accessory;
            }).collect(Collectors.toList());
            accessoryService.saveBatch(accessories);
        }
        //redis
        Set keys=redisTemplate.keys("*_"+projectFinish.getProjectId());
        redisTemplate.delete(keys);

    }

    //老师
    //立项审核页面
    public Page teacherBeginPage(int page,int pageSize,String name){
        //分页构造器
        Page<Project> projectPage =new Page<>(page,pageSize);
        Page<ProTeacherDto> pageInfo =new Page<>();

        //条件查询
        LambdaQueryWrapper<Project> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Project::getName,name);
        queryWrapper.orderByDesc(Project::getDeclareTime);
        projectService.page(projectPage,queryWrapper);




        //对象拷贝
        BeanUtils.copyProperties(projectPage,pageInfo,"records");
        List<Project> records = projectPage.getRecords();

        List<ProTeacherDto> list=records.stream().map((item)->{
             //redis
              ProTeacherDto proTeacherDto = null;
             String key = "teacher_begin"+item.getId();
             proTeacherDto=(ProTeacherDto)redisTemplate.opsForValue().get(key);
             if(proTeacherDto!=null){
                 return proTeacherDto;
             }

            proTeacherDto=new ProTeacherDto();

            BeanUtils.copyProperties(item,proTeacherDto);

            //查询负责人
            String master = proTeacherDtoMapper.getMyMaster(item.getId());
            proTeacherDto.setTutor(master);
            //查询成员
            List<String> members = proTeacherDtoMapper.getMyMember(item.getId());
            proTeacherDto.setMember(members);

            //设置状态

            Logs myLog = proTeacherDtoMapper.getMyLogBegin(item.getId());
            if(myLog.getLevel()==1){
                proTeacherDto.setLevel(0);//学生端为审核中
                proTeacherDto.setStatus("未立项审核");
            }else if(myLog.getLevel()==2){
                proTeacherDto.setLevel(2);
                proTeacherDto.setStatus("立项通过");
            }else if(myLog.getLevel()==3){
                proTeacherDto.setStatus("立项未通过");
            }
            //设置flag 操作（0：不可操作 1：可操作）
            if(myLog.getLevel()==1){
                proTeacherDto.setFlag(1);
            }else{
                proTeacherDto.setFlag(0);
            }
            redisTemplate.opsForValue().set(key,proTeacherDto,60,TimeUnit.MINUTES);
            return proTeacherDto;
        }).collect(Collectors.toList());
        pageInfo.setRecords(list);

        return pageInfo;

    }
    //中期审核
    public Page teacherMidPage(int page,int pageSize,String name){
        //分页构造器
        Page<Project> projectPage =new Page<>(page,pageSize);
        Page<ProTeacherDto> pageInfo =new Page<>();

        //条件查询
        LambdaQueryWrapper<Project> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Project::getName,name);
        queryWrapper.orderByDesc(Project::getDeclareTime);
        projectService.page(projectPage,queryWrapper);



        //对象拷贝
        BeanUtils.copyProperties(projectPage,pageInfo,"records");
        List<Project> records = projectPage.getRecords();

        List<ProTeacherDto> list=records.stream().map((item)->{
             //redis
             ProTeacherDto proTeacherDto=null;
             String key = "teacher_mid"+item.getId();
             proTeacherDto=(ProTeacherDto)redisTemplate.opsForValue().get(key);
             if(proTeacherDto!=null){
                 return proTeacherDto;
             }

             proTeacherDto=new ProTeacherDto();
            BeanUtils.copyProperties(item,proTeacherDto);

            //查询负责人
            String master = proTeacherDtoMapper.getMyMaster(item.getId());
            proTeacherDto.setTutor(master);
            //查询成员
            List<String> members = proTeacherDtoMapper.getMyMember(item.getId());
            proTeacherDto.setMember(members);

            //设置状态

            Logs myLog = proTeacherDtoMapper.getMyLogMid(item.getId());
            List<Accessory> myAccessory = proTeacherDtoMapper.getMyAccessoryMid(item.getId());
            if(myLog.getLevel()==0||myLog.getLevel()==1){
                proTeacherDto.setLevel(0);
                proTeacherDto.setStatus("未中期审核");
            }else if(myLog.getLevel()==2||myLog.getLevel()==3){
                proTeacherDto.setLevel(3);
                proTeacherDto.setStatus("中期审核未通过");
            }else if(myLog.getLevel()==4){
                proTeacherDto.setLevel(4);
                proTeacherDto.setStatus("中期审核通过");
            }
            //设置flag 操作（0：不可操作 1：可操作）
            if(myLog.getLevel()==1){
                proTeacherDto.setFlag(1);
            }else{
                proTeacherDto.setFlag(0);
            }
            redisTemplate.opsForValue().set(key,proTeacherDto,60,TimeUnit.MINUTES);
            return proTeacherDto;
        }).collect(Collectors.toList());
        pageInfo.setRecords(list);

        return pageInfo;

    }
    //结项审核
    public Page teacherEndPage(int page,int pageSize,String name){
        //分页构造器
        Page<Project> projectPage =new Page<>(page,pageSize);
        Page<ProTeacherDto> pageInfo =new Page<>();

        //条件查询
        LambdaQueryWrapper<Project> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Project::getDeclareTime);
        queryWrapper.like(name!=null,Project::getName,name);
        projectService.page(projectPage,queryWrapper);


        //对象拷贝
        BeanUtils.copyProperties(projectPage,pageInfo,"records");
        List<Project> records = projectPage.getRecords();

        List<ProTeacherDto> list=records.stream().map((item)->{
            ProTeacherDto proTeacherDto=null;
             String key = "teacher_end_"+item.getId();
             proTeacherDto=(ProTeacherDto)redisTemplate.opsForValue().get(key);
             if(proTeacherDto!=null){
                 return proTeacherDto;
             }

             proTeacherDto=new ProTeacherDto();

            BeanUtils.copyProperties(item,proTeacherDto);

            //查询负责人
            String master = proTeacherDtoMapper.getMyMaster(item.getId());
            proTeacherDto.setTutor(master);
            //查询成员
            List<String> members = proTeacherDtoMapper.getMyMember(item.getId());
            proTeacherDto.setMember(members);

            //设置状态

            Logs myLog = proTeacherDtoMapper.getMyLogEnd(item.getId());
            List<Accessory> myAccessory = proTeacherDtoMapper.getMyAccessoryEnd(item.getId());
            if(myLog.getLevel()==0|| myLog.getLevel()==1||myLog.getLevel()>3){
                proTeacherDto.setLevel(0);
                proTeacherDto.setStatus("未结项审核");
            }else if(myLog.getLevel()==2){
                proTeacherDto.setLevel(2);
                proTeacherDto.setStatus("结项审核通过");
            }else if(myLog.getLevel()==3){
                proTeacherDto.setLevel(3);
                proTeacherDto.setStatus("结项审核通过");
            }
            //设置flag 操作（0：不可操作 1：可操作）
            if(myLog.getLevel()==1){
                proTeacherDto.setFlag(1);
            }else{
                proTeacherDto.setFlag(0);
            }
            redisTemplate.opsForValue().set(key,proTeacherDto,60,TimeUnit.MINUTES);
            return proTeacherDto;
        }).collect(Collectors.toList());
        pageInfo.setRecords(list);

        return pageInfo;
    }
    //延期审核列表
    public Page teacherExtension(int page,int pageSize,String name){
        //分页构造器
        Page<Project> projectPage =new Page<>(page,pageSize);
        Page<ProTeacherDto> pageInfo =new Page<>();

        //条件查询
        LambdaQueryWrapper<Project> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Project::getDeclareTime);
        queryWrapper.like(name!=null,Project::getName,name);
        projectService.page(projectPage,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(projectPage,pageInfo,"records");
        List<Project> records = projectPage.getRecords();

        List<ProTeacherDto> list=records.stream().map((item)->{
            ProTeacherDto proTeacherDto=null;
            String key ="teacher_extension_"+item.getId();
            proTeacherDto=(ProTeacherDto)redisTemplate.opsForValue().get(key);
            if(proTeacherDto!=null){

                return proTeacherDto;
            }

            proTeacherDto=new ProTeacherDto();

            BeanUtils.copyProperties(item,proTeacherDto);
            //查询负责人
            String master = proTeacherDtoMapper.getMyMaster(item.getId());
            proTeacherDto.setTutor(master);
            //查询成员
            List<String> members = proTeacherDtoMapper.getMyMember(item.getId());
            proTeacherDto.setMember(members);

            //设置状态

            Logs myLog = proTeacherDtoMapper.getMyLogEnd(item.getId());
            if(myLog.getLevel()==5||myLog.getLevel()<4){
                proTeacherDto.setLevel(4);
                proTeacherDto.setStatus("未延期审核");
            }else if(myLog.getLevel()==6){
                proTeacherDto.setLevel(6);
                proTeacherDto.setStatus("延期审核通过");
            }else if(myLog.getLevel()==7){
                proTeacherDto.setLevel(7);
                proTeacherDto.setStatus("延期审核未通过");
            }
            //设置flag 操作（0：不可操作 1：可操作）
            if(myLog.getLevel()==5){//有延期申请
                proTeacherDto.setFlag(1);
            }else{
                proTeacherDto.setFlag(0);
            }

            redisTemplate.opsForValue().set(key,proTeacherDto,60,TimeUnit.MINUTES);
            return proTeacherDto;
        }).collect(Collectors.toList());
        pageInfo.setRecords(list);

        return pageInfo;
    }
    //进展记录（学生端,老师端）

    //修改项目状态
    public void change(Long projectId,int status){
        // 修改日志
        if(status==2) {
            logsMapper.updateStatusWithLevel(projectId, status);
            //删除附件
            LambdaQueryWrapper<Accessory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Accessory::getProjectId, projectId);
            lambdaQueryWrapper.eq(Accessory::getType, status);
            accessoryService.remove(lambdaQueryWrapper);
        }else if(status==1){
            logsMapper.updateStatusWithLevel(projectId, status);
            //删除附件
            LambdaQueryWrapper<Accessory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Accessory::getProjectId, projectId);
            lambdaQueryWrapper.eq(Accessory::getType, status);
            accessoryService.remove(lambdaQueryWrapper);
            //修改大创日志
            logCountMapper.delete(projectId);
            LogCount logCount=new LogCount();
            logCount.setCount(0);
            logCount.setProjectId(projectId);
            logCountService.save(logCount);
        }
        else{//如果立项审核未通过，重新申请
            projectService.removeById(projectId);

        }

        Set keys=redisTemplate.keys("*_"+projectId);
        redisTemplate.delete(keys);

    }
    //修改日志次数
    public void changeLogCount(Long projectId,int count){
        LogCount logCount=new LogCount();
        logCount.setCount(count);
        logCount.setProjectId(projectId);
        logCountService.save(logCount);
        if(count==10){
            logsMapper.updateLogsWithLevel(projectId,1,0);
        }
        Set keys=redisTemplate.keys("*_"+projectId);
        redisTemplate.delete(keys);
    }

    //进入结项页面信息筛选
    public ProPartPlus getEndConcise(ProjectPartDto projectPartDto){
        ProPartPlus proPartPlus=new ProPartPlus();
        proPartPlus.setId(projectPartDto.getId());
        proPartPlus.setName(projectPartDto.getName());
        proPartPlus.setCategory(projectPartDto.getCategory());
        proPartPlus.setDeclareTime(projectPartDto.getDeclareTime());
        //老师
        proPartPlus.setTeacher(projectPartDto.getTeacher());
       // proPartPlus.set
        List<MemberPlus> list=projectPartDto.getMembers().stream().map((item)->{
            MemberPlus pro =new MemberPlus();
            pro.setName(item.getName());
            pro.setUserId(item.getUserId());
            return pro;
        }).collect(Collectors.toList());
        proPartPlus.setMembers(list);
        List<AnnexPlus> annex=projectPartDto.getAccessories().stream().map((item)->{
            AnnexPlus annexPlus=new AnnexPlus();
            annexPlus.setUrl(item.getAccessory());
            annexPlus.setName(item.getName());
            return annexPlus;
        }).collect(Collectors.toList());
        proPartPlus.setAnnex(annex);
        return proPartPlus;

    }
    //项目详情信息筛选
    public ProjectDetailPlus getDetailPlus(ProjectPartDto projectPartDto){
        ProjectDetailPlus projectDetailPlus=new ProjectDetailPlus();
        projectDetailPlus.setId(projectPartDto.getId());
        projectDetailPlus.setCategory(projectPartDto.getCategory());
        projectDetailPlus.setName(projectPartDto.getName());
        projectDetailPlus.setDeclareTime(projectPartDto.getDeclareTime());
        projectDetailPlus.setBrieflno(projectPartDto.getBrieflno());;

        //成员
        //动态位置
         sortMain = 0;
        List<MemberWork> memberWorks= projectPartDto.getMembers().stream().map((item)->{

            MemberWork memberWork=new MemberWork();
            BeanUtils.copyProperties(item,memberWork);
            LambdaQueryWrapper<ProMember> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(ProMember::getUserId,item.getUserId());
            queryWrapper.eq(ProMember::getProjectId,projectPartDto.getId());
            queryWrapper.eq(ProMember::getSort, sortMain++);

            ProMember member = proMemberService.getOne(queryWrapper);
            memberWork.setWork(member.getWork());
            return memberWork;
        }).collect(Collectors.toList());
        projectDetailPlus.setMemberWorks(memberWorks);
        //老师
        LambdaQueryWrapper<UserMember> teacher =new LambdaQueryWrapper<>();
        teacher.eq(UserMember::getUserId,projectPartDto.getTutorId());
        UserMember serviceTeacher = userMemberService.getOne(teacher);
        TeacherMember teacherMember=new TeacherMember();
        teacherMember.setPosition(serviceTeacher.getPosition());
        teacherMember.setDepartment(serviceTeacher.getDepartment());
        teacherMember.setName(serviceTeacher.getName());
        teacherMember.setMajor(serviceTeacher.getMajor());
        teacherMember.setUserId(serviceTeacher.getUserId());
        teacherMember.setPhone(serviceTeacher.getPhone());
        projectDetailPlus.setTeacherPlus(teacherMember);

        //企业老师
        ProETeacherPlus proETeacherPlus=new ProETeacherPlus();
        proETeacherPlus.setName(projectPartDto.getProEteacher().getName());
        proETeacherPlus.setDepartment(projectPartDto.getProEteacher().getDepartment());
        proETeacherPlus.setMajor(projectPartDto.getProEteacher().getMajor());
        proETeacherPlus.setPhone(projectPartDto.getProEteacher().getPhone());
        proETeacherPlus.setPosition(projectPartDto.getProEteacher().getPosition());

        projectDetailPlus.setProETeacherPlus(proETeacherPlus);

        //公告
        List<AnnexPlus> annexPluses=projectPartDto.getAccessories().stream().map((item)->{
            AnnexPlus annexPlus=new AnnexPlus();
            annexPlus.setName(item.getName());
            annexPlus.setUrl(item.getAccessory());
            return annexPlus;
        }).collect(Collectors.toList());
        projectDetailPlus.setAnnexPlus(annexPluses);

        return projectDetailPlus;
    }


}
